<?php

namespace app\api\model;

use app\common\library\IdentityCard;
use app\common\library\Token;
use app\common\model\BaseModel;
use app\common\model\Config;
use EasyWeChat\Factory;
use fast\Random;
use think\facade\Db;
use think\facade\Validate;

class User extends BaseModel
{
    // 表名
    protected $name = 'user';
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
    ];

    /**
     * 小程序登录
     * @params string code
     * @params string iv 偏移量
     * @params string encryptedData 加密串
     * @param $requestData
     * @return array|string[]
     */
    public function wechatLogin($requestData){
        $code = $requestData['code']??'';
        $encryptedData = $requestData['encryptedData']??'';
        $iv = $requestData['iv']??'';
        if(empty($code)  || empty($encryptedData)|| empty($iv)){
            return ['status'=>'0','message'=>'参数错误','result'=>''];
        }
        $wechat_config = config("config_wechat.mini_program");
        if(!$wechat_config){
            return ['status'=>'0','message'=>'请求错误','result'=>''];
        }
        $app = Factory::miniProgram($wechat_config);
        //根据code获取用户 session信息
        /***
         * Array
         * [session_key] => EYt4+b/eyjrOr775rDZ33g==
         * [openid] => o4h_s4ppuOk5vFWYNcaf1GhgyxQU
         */
        $user_data = $app->auth->session($code);
        if(!isset($user_data['session_key'])){
            return ['status'=>'0','message'=>'请求失败','result'=>$user_data];
        }
        //解密信息
        $decryptedData = $app->encryptor->decryptData($user_data['session_key'], $iv, $encryptedData);
        $wx_openid =  $user_data['openid'];   //微信openid
        $nickname  =  $decryptedData['nickName'];  //微信昵称
        $head_img  =  $decryptedData['avatarUrl']; //微信头像

        $user_mes = self::where(['openid'=>trim($wx_openid)])->find();
        //记录本次登录的IP和时间
        $ip = request()->ip();
        $logintime = time();
        if(!empty($user_mes)){
            //登录
            $login_type = 2; //操作类型： 1 注册  2 登录
            $user_id = $user_mes['id'];
//            self::update(['username' => $nickname, 'avatar'=>$head_img, 'updatetime' => time(), 'loginip' => $ip, 'logintime' => $logintime], ['id'=>$user_id]);
            self::update(['updatetime' => time(), 'loginip' => $ip, 'logintime' => $logintime], ['id'=>$user_id]);
        }else{
            //注册
            $login_type = 1; //操作类型： 1 注册  2 登录
            //组装数据
            $inserdate = [
                "username"=>$nickname,
                "avatar"=>$head_img,
                "openid"=>trim($wx_openid),
                "createtime"=>time(),
                'loginip' => $ip,
                'logintime' => $logintime,
                'status' => 'normal',
                'jointime' => time(),
                'joinip' => $ip
            ];
            $user_id = self::insertGetId($inserdate);
        }

        //查询用户信息
        $wx_user_mes = self::where(['id' => $user_id])->field('id,username,avatar,mobile')->find();

        $token = Random::uuid();
        Token::set($token, $wx_user_mes['id'], 2592000);

        //登录成功的事件
//        event("user_login", $wx_user_mes);
        $result_data = array(
            'login_type'=>$login_type,
            'user_mes'=>$wx_user_mes,
            'token' => $token
        );
        return ['status' => 1, 'message' => '登录成功', 'result' => $result_data];
    }

    /**
     * 授权手机号
     * @param $requestData
     * @return array|string[]
     */
    public function getPhoneNumber($requestData){
        $code = $requestData['code']??'';
        $encryptedData = $requestData['encryptedData']??'';
        $iv = $requestData['iv']??'';
        if(empty($code)  || empty($encryptedData)|| empty($iv)){
            return ['status'=>'0','message'=>'参数错误','result'=>''];
        }
        $wechat_config = config("config_wechat.mini_program");
        if(!$wechat_config){
            return ['status'=>'0','message'=>'请求错误','result'=>''];
        }
        $app = Factory::miniProgram($wechat_config);
        //根据code获取用户 session信息
        /***
         * Array
         * [session_key] => EYt4+b/eyjrOr775rDZ33g==
         * [openid] => o4h_s4ppuOk5vFWYNcaf1GhgyxQU
         */
        $user_data = $app->auth->session($code);
        if(!isset($user_data['session_key'])){
            return ['status'=>'0','message'=>'请求失败','result'=>$user_data];
        }
        //解密信息
        $decryptedData = $app->encryptor->decryptData($user_data['session_key'], $iv, $encryptedData);
        if (!$decryptedData || !isset($decryptedData['phoneNumber'])) {
            $this->error('获取手机号失败,请重试!');
        }
        $wx_openid =  $user_data['openid'];   //微信openid
        $mobile  =  $decryptedData['phoneNumber'];

        $wx_user_mes = self::where(['openid' => $wx_openid])->update(['mobile' => $mobile]);
        return ['status' => 1, 'message' => '获取手机号成功', 'result' => $mobile];
    }


    /**
     * 我的首页
     */
    public function mine($requestData, $user){
        if(!$user){
            ['status' => 0, 'message' => '用户不存在', 'result' => ''];
        }
        $data = [
            'id' => $user['id'],
            'username' => $user['username'],
            'avatar' => $user['avatar'],
            'mobile' => $user['mobile'],
            'ID' => sprintf('%06d', $user['id']),
            'wallet'  => $user['wallet'],
            'is_show' => $user['is_show'],
            'basketball_discount' => $user['basketball_discount'],
            'badminton_discount' => $user['badminton_discount'],
        ];
        return ['status' => 1, 'message' => '操作成功', 'result' => $data];
    }

    /**
     * 意见反馈
     */
    public function feedback($requestData, $user){
        $content = $requestData['content']??'';
        $images = $requestData['images']??'';
        if(!$content || !$images){
            return ['status' => 0, 'message' => '内容或图片为空', 'result' => ''];
        }
        $last_feedback = Feedback::where(['is_delete' => 1, 'user_id' => $user['id']])->value('createtime');
        if($last_feedback){
            $time = bcsub(time(), $last_feedback, 0);
            if($time < 5){
                return ['status' => 0, 'message' => '提交过于频繁', 'result' => ''];
            }
        }
        $feedbak = [
            'user_id' => $user['id'],
            'feed_content' => $content,
            'feed_images' => $images,
            'createtime' => time(),
        ];
        $res = Feedback::insert($feedbak);
        if($res){
            return ['status' => 1, 'message' => '操作成功', 'result' => ''];
        }else{
            return ['status' => 0, 'message' => '操作失败', 'result' => ''];
        }
    }

    /**
     * 公共参数
     */
    public function config($requestData){
        $config = Config::where('name', 'in', 'platform_banner,vip_desc,user_agreement,privacy_policy,about_us,service_phone,service_wechat,service_qrcode,system_venue,business_time,system_address,coupon_money')->column('value', 'name');
        if(isset($config['platform_banner'])){
            $config['platform_banner'] = explode(',', $config['platform_banner']);
        }
        return ['status' => 1, 'message' => '操作成功', 'result' => $config];
    }

    /**
     * @param array $where
     * @param string $field
     * @return array|mixed|\think\Model|null
     */
    public function userFind($where = [], $field = '*'){
        return $this->where($where)->field($field)->find();
    }

}
